// src/utils/request.js
import axios from 'axios'
import { token, authHandler } from './authUtils'  // 修正导入方式
import router from '@/router'
import { ElMessage } from 'element-plus'  // 添加ElMessage导入

const apiClient = axios.create({
    baseURL: 'http://localhost:8000',
    timeout: 10000,
})

// 请求拦截器
apiClient.interceptors.request.use(
    config => {
        if (token.value) {
            config.headers['Authorization'] = `Bearer ${token.value}`
        }else{
            const accessToken = localStorage.getItem('access_token') // 新增
            config.headers['Authorization'] = `Bearer ${accessToken}`
        }
        return config
    }
)

// 响应拦截器
apiClient.interceptors.response.use(
    response => response,
    async error => {
        const originalRequest = error.config
        
        if (error.response?.status === 401 && !originalRequest._retry) {
            originalRequest._retry = true // 标记请求已重试过,避免死循环
            
            try {
                const refresh = localStorage.getItem('refresh_token')
                if (!refresh) {
                    throw new Error('No refresh token')
                }
                
                const response = await axios.post('/api/users/refresh-token/', {
                    refresh: refresh
                })
                
                if (response.data.status === 'success') {
                    // 更新 token
                    localStorage.setItem('access_token', response.data.access) 
                    token.value = response.data.access
                    
                    // 重试原请求
                    originalRequest.headers['Authorization'] = `Bearer ${response.data.access}`
                    return apiClient(originalRequest)
                }
            } catch (err) {
                // 刷新失败,清除认证信息并跳转登录
                authHandler.clearAuthInfo()
                router.push('/login')
                return Promise.reject(error)
            }
        }
        
        if (error.response?.status === 403) {
            ElMessage.error('没有权限访问该资源')
        }
        if (error.response?.status === 404) {
            ElMessage.error('请求的资源不存在') 
        }
        if (error.response?.status === 400) {
            ElMessage.error('请求参数错误')
        }
        return Promise.reject(error)
    }
)

export default apiClient